package com.googlecode.yoohoo.xmppcore.protocol.stream;

import java.util.List;

import com.googlecode.yoohoo.xmppcore.protocol.XmppProtocolException;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.Attribute;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.IXmppParser;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.IXmppParserFactory;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.ProtocolKey;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.XmppParserAdapter;
import com.googlecode.yoohoo.xmppcore.protocol.stanza.error.BadRequest;

public class BindParserFactory implements IXmppParserFactory<Bind> {
	@Override
	public IXmppParser<Bind> createParser() {
		return new BindParser();
	}

	@Override
	public ProtocolKey getProtocolKey() {
		return Bind.PROTOCOL_KEY;
	}
	
	private class BindParser extends XmppParserAdapter<Bind> {
		private static final String PATH_BIND_JID = "bind/jid";
		private static final String PATH_BIND_RESOURCE = "bind/resource";
		private static final String PATH_BIND = "bind";
		private Bind bind;
		
		@Override
		public void processAttributes(String path, List<Attribute> attributes) {
			if (PATH_BIND.equals(path)) {
				if (attributes.size() > 0) {
					throw new XmppProtocolException(new BadRequest("Invalid attributes for 'bind' element."));
				}
				
				bind = new Bind();
			} else if (PATH_BIND_RESOURCE.equals(path)) {
				if (attributes.size() > 0) {
					throw new XmppProtocolException(new BadRequest("Invalid attributes for 'resource' element."));
				}
			} else if (PATH_BIND_JID.equals(path)) {
				if (attributes.size() > 0) {
					throw new XmppProtocolException(new BadRequest("Invalid attributes for 'jid' element."));
				}
			} else {
				throw new XmppProtocolException(new BadRequest(String.format("Invalid parsing path '%s'", path)));
			}
		}
		
		@Override
		public void processText(String path, String text) {
			if (PATH_BIND_RESOURCE.equals(path) && text != null) {
				bind.setResource(text);
			}
			
			if (PATH_BIND_JID.equals(path) && text != null) {
				bind.setJid(text);
			}
		}

		@Override
		public Bind getObject() {
			return bind;
		}

	}

}
